<?php

declare(strict_types=1);

namespace app\admin\service\science;

use app\common\model\ProjectModel;
use Dengje\Pxy\BaseService;

class ProjectService extends BaseService
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new ProjectModel();
    }

    public function list()
    {
        $where = [];
        $order = ['id' => 'desc'];
        $name = request()->get('title', '');
        $id = request()->get('id', '');
        if ($name) $where[] = ['name', 'like', '%' . $name . '%'];
        if ($id) $where[] = ['id', '=', $id];
        $list = $this->model->where($where)->order($order)->paginate(request()->get('page_size/d', 10));
        return $list;
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->find();
        return $detail;
    }

    public function create($request)
    {
        $data = $this->preExcludeFields($request->param());
        $model = [
            'name' => $data['name'],
            'app_id' => $data['app_id'],
            'secret' => $data['secret'],
            'update_time' => time(),
            'create_time' => time()
        ];
        $id = $this->model->insertGetId($model);
        return $id;
    }

    public function update($id, $request)
    {
        $data = $this->preExcludeFields($request->param());
        $model = [
            'name' => $data['name'],
            'app_id' => $data['app_id'],
            'secret' => $data['secret'],
            'update_time' => time()
        ];
        $this->model->where('id', $id)->update($model);
        return $id;
    }

    public function delete($id)
    {
        // 检查是否有文章使用该分类
        $this->model->where('id', $id)->delete();
        return success('删除成功');
    }

    public function select()
    {
        $list = $this->model->field('id, name')->select();
        return $list;
    }
}